<?php

namespace Lambq\Tcpclient\Panel;

use Swoole\Coroutine\Client;
use function Swoole\Coroutine\run;

class Tcp
{
    protected $host = null;
    protected $port = null;

    protected $timeout = 0;

    protected $clean;

    protected $socket = false;
    protected $setData;

    protected $writer;                  // An instance of the BinaryTreeNodeWriter class.
    protected $reader;                  // An instance of the BinaryTreeNodeReader class.

    public function __construct()
    {
        $this->host         = config('tcpClient.host');
        $this->port         = config('tcpClient.port');
        $this->timeout      = config('tcpClient.timeout');
        $this->connect      = config('tcpClient.connect');
        $this->write        = config('tcpClient.write');
        $this->read         = config('tcpClient.read');
        $this->ssl          = config('tcpClient.ssl');
        $this->socket       = new Client(SWOOLE_SOCK_TCP);
    }

    // 设备set内容
    public function set()
    {
        $this->setData  = [
            'timeout'           => $this->timeout,
            'connect_timeout'   => $this->connect,
            'write_timeout'     => $this->write,
            'read_timeout'      => $this->read,
            'ssl_verify_peer'   => $this->ssl,
        ];
        return $this;
    }

    // 设置代理
    public function proxy($host, $port, $name = null, $pass = null)
    {
        if ($name != '' && $pass != '')
        {
            $array  = [
                'socks5_host' => $host,
                'socks5_port' => $port,
                'socks5_username' => $name,
                'socks5_password' => $pass,
            ];
            $this->setData  = array_merge($this->setData, $array);
            return $this;
        } else {
            $array  = [
                'socks5_host' => $host,
                'socks5_port' => $port,
            ];
            $this->setData  = array_merge($this->setData, $array);
            return $this;
        }
    }

    // 连接tcp
    public function connect()
    {
        $this->reader = $this->socket->connect($this->host, $this->port);
        if (!$this->reader)
        {
            $this->socket->close();
            $this->socket   = false;
            return false;
        }

        return $this;
    }

    // 读取tcp 数据
    public function connectToReceive($proc)
    {
        if (!$this->socket->isConnected()) {
            $proc([
                'status'    => 'fail',
                'data'      => '',
                'msg'       => [
                    'type'  => 'socket',
                    'code'  => $this->socket->errCode,
                    'res'   => '客户端断开于服务端的连接！'
                ]
            ]);
        }
        while (true) {
            $data = $this->socket->recv();
            if (strlen($data) > 0) {
                echo "接收到数据内容：";
                $proc([
                    'status'    => 'ok',
                    'data'      => $data,
                    'msg'       => ''
                ]);
                var_dump($data);
//                $socket->send(time() . PHP_EOL);
                echo "接收到数据"."\n";
            } else {
                //发生错误或对端关闭连接，本端也需要关闭
                if ($data === '' || $data === false) {
                    $code   = null;
                    $res    = null;
                    if ($this->socket->errCode) {
                        $code   = $this->socket->errCode;
                    }

                    if ($this->socket->errMsg) {
                        $res    = $this->socket->errMsg;
                    }

                    $proc([
                        'status'    => 'fail',
                        'data'      => $data,
                        'msg'       => [
                            'type'  => 'socket',
                            'code'  => $code,
                            'res'   => $res
                        ]
                    ]);
                    echo "errCode: {$this->socket->errCode}\n";
                    $this->socket->close();
                    $this->socket = false;
                    break;
                } else {
                    $proc([
                        'status'    => 'fail',
                        'data'      => '',
                        'msg'       => [
                            'type'  => 'socket',
                            'code'  => $this->socket->errCode,
                            'res'   => '对端服务器，关闭连接了！'
                        ]
                    ]);
                    echo '接收 WA server 返回data！'. var_dump($data)."\n";
                    $this->socket->close();
                    $this->socket = false;
                    break;
                }
            }
        }
    }

    // 发送tcp 数据
    public function connectToSend($msg)
    {
        if (!$this->socket->isConnected()) {
            return [
                'status'    => 'fail',
                'data'      => '',
                'msg'       => [
                    'type'  => 'socket',
                    'code'  => $this->socket->errCode,
                    'res'   => '客户端断开于服务端的连接！'
                ]
            ];
        }
        $res = $this->socket->send($msg);
        if ($res)
        {
            return [
                'status'    => 'ok',
                'data'      => '客户端发送数据已到达服务端！',
                'msg'       => null
            ];
        }

        return [
            'status'    => 'fail',
            'data'      => '',
            'msg'       => [
                'type'  => 'socket',
                'code'  => $this->socket->errCode,
                'res'   => '客户端发送数据未到达服务端！'
            ]
        ];
    }
}
